package com.nsu.tly.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @Description:
 * @Author: Elder Tang
 * @Date: 2021/7/21 14:59
 */
@Controller
public class UploadController {
    @RequestMapping("/upLoad")
    public String upLoad(MultipartFile myfile, HttpServletRequest request, Model model) {
        //获取文件原始文件名
        String oldName=myfile.getOriginalFilename();
        //获取文件保存路径
        String path=request.getServletContext().getRealPath("/static");
        File filepath=new File(path);
        //判断文件目录是否存在，若不存在则创建该目录
        if(!filepath.exists()){
            filepath.mkdirs();
        }
        //使用UUID类方法构造新的文件名，防止保存时文件名冲突
        String newName= UUID.randomUUID()+"_"+oldName;
        //设置文件最终保存位置及对应文件名
        File newFile =new File(filepath+File.separator+newName);
        try {

            //上传并保存文件到指定位置
            myfile.transferTo(newFile);
            model.addAttribute("msg","文件上传成功！");
            return "message";
        }catch (IOException e){
            model.addAttribute("msg","文件上传失败！");
            return "message";
        }
    }
}
